﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using DevExpress.Web.ASPxHeadline;
using DevExpress.Web.ASPxClasses;
using DevExpress.Web.ASPxCallback;
using DevExpress.Web.ASPxHtmlEditor;

using LMD.Constant;
using LMD.Lib.DataClass;
using LMD.Lib.Interface;
using LMD.Lib.Controls;

public partial class CompanyProfile : ICPGeneralPage
{
    public CompanyProfileData m_cpd;
    public ContactInfoData m_cid;

    #region Properties
    public String m_sxCompanyId
    {
        get
        {
            if (!String.IsNullOrEmpty(Request.QueryString["cid"]))
            {
                return Request.QueryString["cid"];
            }
            else
            {
                return String.Empty;
            }
        }
    }

    public String m_sxFilterMode
    {
        get
        {
            if (!String.IsNullOrEmpty(Request.QueryString["mode"]))
            {
                return Request.QueryString["mode"];
            }
            else
            {
                return String.Empty;
            }
        }
    }

    public String m_sxFilterValue
    {
        get
        {
            if (!String.IsNullOrEmpty(Request.QueryString["value"]))
            {
                return Request.QueryString["value"];
            }
            else
            {
                return String.Empty;
            }
        }
    }

    public int m_iPageNumber
    {
        get
        {
            if (!String.IsNullOrEmpty(Request.QueryString["page"]))
            {
                try
                {
                    return int.Parse(Request.QueryString["page"]);
                }
                catch
                {
                    return 1;
                }
            }
            else
            {
                return 1;
            }
        }
    }

    public String m_sxReportId
    {
        get
        {
            if (!String.IsNullOrEmpty(Request.QueryString["rpt"]))
            {
                return Request.QueryString["rpt"];
            }
            else
            {
                return String.Empty;
            }
        }
    }
    #endregion Properties

    #region Event Handlers
    protected override void Page_Load(object sender, EventArgs e)
    {
        base.Page_Load(sender, e);

        Page.Title = "ICP Lintasarta: Company Profile";
        if (!IsPostBack && !IsCallback)
        {
            if (String.IsNullOrEmpty(m_sxCompanyId))
            {
                pnlCompanyList.InnerHtml = InitCompanyList();
            }
            else
            {
                pnlCompanyTitle.InnerHtml = InitCompanyProfile();                
            }
        }
        hteBriefDesc.CreateDefaultToolbars(true);
        hteBriefDesc.Toolbars[1].Items[0].Visible = false;
    }
    protected void cbkBasicInfo_Callback(object sender, CallbackEventArgs e)
    {
        System.Threading.Thread.Sleep(KGlobal.AJAX_WAIT_TIME);
        e.Result = Handle_BasicInfo(e.Parameter);
    }
    protected void cbkContactInfo_Callback(object sender, CallbackEventArgs e)
    {
        System.Threading.Thread.Sleep(KGlobal.AJAX_WAIT_TIME);
        e.Result = Handle_ContactInfo(e.Parameter);
    }
    protected void cbkBriefDesc_Callback(object sender, CallbackEventArgs e)
    {
        System.Threading.Thread.Sleep(KGlobal.AJAX_WAIT_TIME);
        e.Result = Handle_BriefDesc(e.Parameter);
    }
    #endregion Event Handlers

    #region Custom Methods
    private String InitCompanyList()
    {
        String sxOutput = String.Empty;

        Cached.CompanyTable ccCompany = new Cached.CompanyTable();

        DataTable dtCompanyList = ccCompany.GetCompanyCompleteList();

        int iPageNumber = m_iPageNumber;
        int iPageSize = KGlobal.DEFAULT_PAGESIZE;

        int iStart = (iPageNumber - 1) * iPageSize;
        int iEnd = ((iPageNumber) * iPageSize) - 1;

        String sxFilterLink = String.Empty;
        String sxPagerLink = String.Empty;

        if (String.IsNullOrEmpty(m_sxFilterMode))
        {
            sxFilterLink =
                CustomControls.Create_AlphabetLink(
                    "CompanyProfile.aspx",
                    String.Format("mode={0}&value", "start"),
                    String.Empty);
            sxPagerLink =
                CustomControls.Create_PagerLink("CompanyProfile.aspx",
                "?page", iPageNumber, dtCompanyList.Rows.Count, iPageSize);
        }
        else
        {
            if (m_sxFilterMode.ToUpper() == "START")
            {
                dtCompanyList = ccCompany.GetCompanyList_NameStartsWith(m_sxFilterValue);
                sxFilterLink = CustomControls.Create_AlphabetLink(
                    "CompanyProfile.aspx", String.Format("mode={0}&value", m_sxFilterMode), m_sxFilterValue);
            }
            else if (dtCompanyList.Columns.Contains(m_sxFilterMode.ToUpper()))
            {
                dtCompanyList = ccCompany.GetCompanyList_Categorized(m_sxFilterValue, m_sxFilterMode);

                DataTable dtDistinct = ccCompany.GetCompanyCompleteList().DefaultView.ToTable(true, m_sxFilterMode);
                List<String> lsDistinctValue = new List<String>();

                foreach (DataRow dr in dtDistinct.Rows)
                {
                    lsDistinctValue.Add(dr[0].ToString());
                }

                lsDistinctValue.Sort();

                sxFilterLink = CustomControls.Create_CategoryLink(
                    "CompanyProfile.aspx", String.Format("mode={0}&value", m_sxFilterMode),
                    lsDistinctValue, m_sxFilterValue);
            }
            else
            {
                sxFilterLink =
                    CustomControls.Create_AlphabetLink(
                        "CompanyProfile.aspx",
                        String.Format("mode={0}&value", "start"),
                        String.Empty);
            }

            sxPagerLink =
                CustomControls.Create_PagerLink(
                    String.Format("CompanyProfile.aspx?mode={0}&value={1}", m_sxFilterMode, m_sxFilterValue),
                    "&page", iPageNumber, dtCompanyList.Rows.Count, iPageSize);
        }

        sxOutput += sxFilterLink;
        sxOutput += sxPagerLink;

        for (int i = iStart; i <= iEnd; i++)
        {
            if (i >= dtCompanyList.Rows.Count)
                break;

            DataRow dr = dtCompanyList.Rows[i];

            CompanyProfileData cpd = new CompanyProfileData();
            cpd.ID = dr.ReadInt("CUSTOMER_ID");
            cpd.sxCompanyName = dr.ReadString("COMPANY_NAME");
            cpd.sxCAREmployeeNo = dr.ReadString("CAR_EMPLOYEE_NO");
            cpd.sxCARName = dr.ReadString("CAR_NAME");
            cpd.sxSalesEmployeeNo = dr.ReadString("SALES_EMPLOYEE_NO");
            cpd.sxSalesName = dr.ReadString("SALES_NAME");
            sxOutput += cpd.BuildCompanyItem();
        }

        sxOutput += sxPagerLink;
        sxOutput += sxFilterLink;

        return sxOutput;
    }

    private String InitCompanyProfile()
    {
        int iCompanyId = int.Parse(m_sxCompanyId);

        Cached.CompanyTable ccCompany = new Cached.CompanyTable();
        m_cpd = ccCompany.GetCompanyProfileData(iCompanyId, true);

        m_cid = new ContactInfoData();
        m_cid.ID = -1;
        m_cid.CompanyID = int.Parse(m_sxCompanyId);

        String sxOutput = String.Empty;

        sxOutput = String.Format(
            "<img src=\"upload/company/{0}.jpg\" alt=\"change company logo\" onclick=\"changeCompanyLogo();\"  onerror=\"setEmptyCompanyAvatar(this);\" class=\"cpP\" style=\"cursor:pointer;\" /><span id=\"cp_Header\">{1}</span>",
            m_cpd.ID.ToString(), m_cpd.sxCompanyName);
        return sxOutput;
    }

    private String Handle_BasicInfo(String sxParameter)
    {
        String sxReturn = String.Empty;

        String[] sxSplitted = sxParameter.Split(new String[] { KGlobal.DELIMITER }, StringSplitOptions.None);
        int iCompanyId = int.Parse(m_sxCompanyId);

        Cached.CompanyTable ccCompany = new Cached.CompanyTable();
        m_cpd = new CompanyProfileData();
        m_cpd.ID = iCompanyId;

        switch (sxSplitted[0].ToUpper())
        {
            case "EDIT":
                m_cpd = ccCompany.GetCompanyProfileData(iCompanyId, true);
                sxReturn = m_cpd.BuildEditor_BasicInfo();
                break;
            case "SAVE":
                UpdateBasicInfo(sxSplitted);
                m_cpd = ccCompany.GetCompanyProfileData(iCompanyId, true);
                sxReturn = m_cpd.BuildFieldSet_BasicInfo();
                sxReturn += KGlobal.DELIMITER + m_cpd.sxSummary;
                break;
            case "DISCARD":
                m_cpd = ccCompany.GetCompanyProfileData(iCompanyId);
                sxReturn = m_cpd.BuildFieldSet_BasicInfo();
                sxReturn += KGlobal.DELIMITER + m_cpd.sxSummary;
                break;
            case "ADD":
                int iLastControlId = int.Parse(sxSplitted[1]);
                iLastControlId++;
                String sxControlId = m_sxCompanyId + "_" + (iLastControlId).ToString();
                sxReturn = CustomControls.BuildEditor_ComboBoxAndText(sxControlId, KLOV.CompanyProfile.BASICINFOTYPE, KControl.INPUT_ID, null, null, null, TextboxType.FreeText);
                break;
            case "CHANGELOGO":
                sxReturn = CompanyProfileManager.BuildEditor_CompanyLogoPopup(m_sxCompanyId);
                break;
        }

        return sxReturn;
    }

    private void UpdateBasicInfo(String[] sxSplitted)
    {
        for (int i = 1; i < sxSplitted.Length; i++) // START FROM INDEX 1
        {
            String[] sxParsed = sxSplitted[i].Split(new String[] { KGlobal.NEWLINE }, StringSplitOptions.None);

            if (sxParsed.Length > 2)
            {
                m_cpd.AddCustomData(sxParsed[1], sxParsed[2]);
            }
        }

        DBQuery.CompanyTable.UpdateCustomData(m_cpd);
    }

    private String Handle_ContactInfo(String sxParameter)
    {
        String[] sxSplitted = sxParameter.Split(new String[] { KGlobal.DELIMITER }, StringSplitOptions.None);
        String[] sxIDSplitted = null;
        String sxReturn = String.Empty;
        int iContactId = 0;
        bool IsNewCP = false;
        Cached.ContactPersonTable ccCP = new Cached.ContactPersonTable();

        switch (sxSplitted[0].ToUpper())
        {
            case "EDIT":
                sxIDSplitted = sxSplitted[1].Split('_');
                iContactId = int.Parse(sxIDSplitted[0]);
                IsNewCP = sxIDSplitted[1].ToUpper() == KGlobal.YES;
                m_cid = ccCP.GetContactInfoData(iContactId, IsNewCP, true);
                sxReturn += m_cid.BuildEditor_ContactInfo();
                break;
            case "SAVE":
                sxIDSplitted = sxSplitted[1].Split('_');
                iContactId = int.Parse(sxIDSplitted[0]);
                UpdateContactInfo(sxSplitted);
                m_cid = ccCP.GetContactInfoData(m_cid.ID, m_cid.IsNewCP, true);
                sxReturn += m_cid.ID + "_" + (m_cid.IsNewCP ? KGlobal.YES : KGlobal.NO);
                sxReturn += KGlobal.DELIMITER + m_cid.BuildFieldSet_ContactInfo();
                break;
            case "DISCARD":
                sxIDSplitted = sxSplitted[1].Split('_');
                iContactId = int.Parse(sxIDSplitted[0]);
                IsNewCP = sxIDSplitted[1].ToUpper() == KGlobal.YES;
                m_cid = ccCP.GetContactInfoData(iContactId, IsNewCP);
                m_cid.CompanyID = int.Parse(m_sxCompanyId);
                sxReturn += m_cid.ID + "_" + (m_cid.IsNewCP ? KGlobal.YES : KGlobal.NO);
                sxReturn += KGlobal.DELIMITER + m_cid.BuildFieldSet_ContactInfo(); 
                //sxReturn = m_cid.ID + KGlobal.DELIMITER + m_cid.BuildFieldSet_ContactInfo();
                break;
            case "ADD":
                ContactInfoData cidNew = new ContactInfoData();
                cidNew.ID = -1;
                sxReturn += cidNew.BuildEditor_ContactInfo();
                break;
            case "ADDINFO":
                int iLastControlId = int.Parse(sxSplitted[1]);
                iLastControlId++;
                String sxControlId = "cpinfo_" + (iLastControlId).ToString();
                sxReturn = CustomControls.BuildEditor_ComboBoxAndText(sxControlId, 
                    KLOV.CompanyProfile.CONTACTINFOTYPE, KControl.INPUT_ID, null, null, null);
                break;
            case "SHOW":
                sxIDSplitted = sxSplitted[1].Split('_');
                iContactId = int.Parse(sxIDSplitted[0]);
                IsNewCP = sxIDSplitted[1].ToUpper() == KGlobal.YES;
                m_cid = ccCP.GetContactInfoData(iContactId, IsNewCP);
                sxReturn = m_cid.BuildFieldSet_ContactInfo();
                break;
        }

        return sxReturn;
    }

    private void UpdateContactInfo(String[] sxSplitted)
    {
        m_cid = new ContactInfoData();

        String[] sxIDSplitted = sxSplitted[1].Split('_');
        m_cid.ID = int.Parse(sxIDSplitted[0]);
        m_cid.CompanyID = int.Parse(m_sxCompanyId);
        m_cid.IsNewCP = sxIDSplitted[1].ToUpper() == KGlobal.YES;

        for (int i = 2; i < sxSplitted.Length; i++) // START FROM INDEX 2
        {
            String[] sxParsed = sxSplitted[i].Split(new String[] { KGlobal.NEWLINE }, StringSplitOptions.None);

            if (sxParsed.Length > 2)
            {
                m_cid.AddCustomData(sxParsed[1], sxParsed[2]);
            }
            else
            {
                switch (sxParsed[0].ToUpper())
                {
                    case KCompanyProfile.NAMA_KONTAK:
                        m_cid.sxContactName = sxParsed[1];
                        break;
                    case KCompanyProfile.GENDER_KONTAK:
                        m_cid.Sex = (Gender)Convert.ToInt32(sxParsed[1]);
                        break;
                    case "HF_" + KCompanyProfile.JABATAN_KONTAK:
                        m_cid.JobPositionID = int.Parse(sxParsed[1]);
                        break;
                    case KCompanyProfile.TELEPON_KONTAK:
                        m_cid.sxPhoneNumber = sxParsed[1];
                        break;
                    case KCompanyProfile.PONSEL_KONTAK:
                        m_cid.sxCellPhoneNumber = sxParsed[1];
                        break;
                    case KCompanyProfile.EMAIL_KONTAK:
                        m_cid.sxEmailAddress = sxParsed[1];
                        break;
                    case KCompanyProfile.CP_TEKNIS:
                        m_cid.IsCPTeknis = sxParsed[1].ToUpper() == KGlobal.YES;

                        // New CP Teknis is not considered as new CP, because it will be saved to ISDS Database
                        m_cid.IsNewCP = m_cid.IsCPTeknis ? false : m_cid.IsNewCP;
                        break;
                }
            }
        }

        DBQuery.ContactPersonTable.SaveContactChanges(m_cid);
        Cached.ContactPersonTable ccCP = new Cached.ContactPersonTable();
        ccCP.RemoveCache();
    }

    private String Handle_BriefDesc(String sxParameter)
    {
        String sxReturn = String.Empty;

        String[] sxSplitted = sxParameter.Split(new String[] { KGlobal.DELIMITER }, StringSplitOptions.None);

        CompanyProfileData cpd = new CompanyProfileData();
        cpd.ID = int.Parse(m_sxCompanyId);

        switch (sxSplitted[0].ToUpper())
        {
            case "EDIT":
                sxReturn = cpd.GetBriefDesc();
                break;
            case "SAVE":
                DBQuery.CompanyTable.InsertCustomerBriefDesc(cpd.ID, sxSplitted[1]);
                sxReturn = cpd.GetBriefDesc();
                break;
            case "DISCARD":
                sxReturn = cpd.GetBriefDesc();
                break;
        }

        return sxReturn;
    }

    protected override void DoSearch(String sxSearchQuery)
    {
        String sxOutput = String.Empty;

        Cached.CompanyTable ccCompany = new Cached.CompanyTable();

        DataTable dtCompanyList = new DataView(
            ccCompany.GetCompanyCarSalesList(),
            String.Format("COMPANY_NAME like '%{0}%'", sxSearchQuery),
            "COMPANY_NAME asc",
            DataViewRowState.CurrentRows).ToTable();

        for (int i = 0; i < dtCompanyList.Rows.Count; i++)
        {
            DataRow dr = dtCompanyList.Rows[i];

            CompanyProfileData cpd = new CompanyProfileData();
            cpd.ID = dr.ReadInt("CUSTOMER_ID");
            cpd.sxCompanyName = dr.ReadString("COMPANY_NAME");
            cpd.sxCAREmployeeNo = dr.ReadString("CAR_EMPLOYEE_NO");
            cpd.sxCARName = dr.ReadString("CAR_NAME");
            cpd.sxSalesEmployeeNo = dr.ReadString("SALES_EMPLOYEE_NO");
            cpd.sxSalesName = dr.ReadString("SALES_NAME");
            sxOutput += cpd.BuildCompanyItem();
        }

        pnlCompanyList.InnerHtml = sxOutput;
    }
    #endregion Custom Methods

}
